layui.use(['laydate', 'form', 'layer'], function () {
  var form = layui.form;
  var layer = layui.layer;
  var table_tby = document.getElementById("table-tby");
  var Tr = document.getElementById("Tr");
  var category = document.getElementById("category");
  var brand = document.getElementById("brand");
  var select_button_div = document.getElementById("select_button_div");
  var opposite = document.getElementById("opposite");
  var find_people = document.getElementById("find_people");
  var repository_opposite_div = document.getElementById("repository_opposite_div");
  var repository_opposite = document.getElementById("repository_opposite");
  var OutStorage_num = document.getElementById("OutStorage_num");
  var OutStorage_button = document.getElementById("OutStorage_button");
  var typical = document.getElementById("typical");
  var model = document.getElementById("model");
  var workId = document.getElementById("workId");
  var RepositoryDiv = document.getElementById("repository");
  var repository = app.getUserGlobalInfo();
  var repository_List = repository.repositoryList;
  var typeUrl;

  // 获取category的select
  $.ajax({
    url: app.ServerUrl + 'v1/type/getAllCategory',
    type: "get",
    contentType: "application/json;charset=UTF-8",
    dataType: "json",
    async: true,
    headers: {
      "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
    },
    data: {},
    success: function (data) {
      // console.log(data.objs[0])
      var repositoryHtml = '<option>请选择来源仓库</option>';

      for (let i = 0; i < repository_List.length; i++) {
        repositoryHtml +=
          '<option value="' + repository_List[i].repositoryId + '">' +
          repository_List[i].repositoryName +
          '</option>'
      }
      RepositoryDiv.innerHTML = repositoryHtml;
      form.render("select")
    },
    error: function (e) {
      console.log(e.statusText)
    }

  })


  // category选择后渲染type
  form.on('select(category)', function (data) {
    var managerId = app.getManagerId()
    let SelectValue = data.value;
    localStorage.setItem("OutStorage_categoryId", SelectValue);
    if (SelectValue == 1) {
      typeUrl = 'v1/type/getTypicalByCategoryId/1?managerId=' + managerId;
      Ajax_category(typeUrl);
    } else if (SelectValue == 2) {
      typeUrl = 'v1/type/getTypicalByCategoryId/2?managerId=' + managerId;
      Ajax_category(typeUrl);
    }
  });

  // category的ajax
  function Ajax_category(Url) {
    $.ajax({
      url: app.ServerUrl + Url,
      type: "get",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      async: true,
      headers: {
        "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
      },
      data: {},
      success: function (data) {
        // console.log(data.objs)
        var typeData = data.objs[0];
        var typeHtml = "<option>请选择类型</option>";


        var typicalNameArray = [];
        for (let i = 0; i < typeData.length; i++) {
          if (typicalNameArray.indexOf(typeData[i].typicalName) != -1) {
            continue;
          }
          typicalNameArray.push(typeData[i].typicalName);
        }
        for (var item in typicalNameArray) {
          typeHtml += '<option value="' + typicalNameArray[item] + '" >' +
            typicalNameArray[item] +
            '</option>'
        }

        typical.innerHTML = typeHtml;
        form.render("select")
      },
      error: function (e) {
        console.log(e.statusText)
      }

    })
  }

  // brand选择后渲染typical
  form.on('select(typical)', function (data) {
    // console.log(data.value)
    let SelectValue = data.value;
    Ajax_typical(SelectValue);
    // typical选择后渲染model
    form.on('select(brand)', function (data) {
      // console.log(data.value)
      // 使用brand的名字来进行渲染model
      var brand = data.value;
      Ajax_brand(SelectValue);
      form.on('select(model)', function (data) {
        // console.log(data)
        var model = data.value;
      });
    });
  });

  // repository的select
  form.on('select(repository)', function (data) {
    // console.log(data)
    var repository = data.value;
  });

  // select_button的按钮
  form.on('submit(select_button)', function (data) {
    var Info = data.field;
    var user_Info = app.getUserGlobalInfo();
    opposite.classList.remove("layui-hide");
    $.ajax({
      url: app.ServerUrl + 'v1/repository/getThingsInRepositoryByCondition',
      type: "get",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      async: true,
      headers: {
        "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
      },
      data: {
        categoryId: Info.category,
        repositoryId: Info.repository_mine,
        typicalId: Info.typicalId,
        userId: user_Info.userId
      },
      success: function (data) {
        // console.log(data.objs[0])
        var typeData = data.objs[0];
        var typeHtml = "";
        for (let i = 0; i < typeData.length; i++) {
          typeHtml +=
            '<tr>' +
            '<td> ' + typeData[i].imei + ' </td>  <' +
            'td > ' + typeData[i].categoryName + ' </td>  <' +
            'td > ' + typeData[i].typicalName + ' </td> <' +
            'td > ' + typeData[i].brand + ' </td> <' +
            'td > ' + typeData[i].typicalModel + ' </td>' +
            '</tr>'
        }
        $('#tabale-thd').removeClass('layui-hide');
        table_tby.innerHTML = typeHtml;
      },
      error: function (e) {
        console.log(e.statusText)
      }

    })
  })

  // typical的ajax
  function Ajax_typical(typicalName) {
    var categoryId = localStorage.getItem("OutStorage_categoryId")
    var managerId = app.getManagerId()
    $.ajax({
      url: app.ServerUrl + 'v1/type/getMaterialBrandAndModelPoByTypicalName/' +
        typicalName + "?managerId=" + managerId + "&categoryId=" + categoryId,
      type: "get",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      async: true,
      headers: {
        "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
      },
      data: {},
      success: function (data) {
        // console.log(data.objs[0])
        var typeData = data.objs[0];
        var typeHtml = "<option>请选择品牌</option>";
        for (let i = 0; i < typeData.length; i++) {
          typeHtml += '<option value="' + typeData[i].brand + '">' +
            typeData[i].brand +
            '</option>'
        }
        brand.innerHTML = typeHtml;
        form.render("select")
      },
      error: function (e) {
        console.log(e.statusText)
      }

    })
  }

  // brand的ajax
  function Ajax_brand(typicalName) {
    var categoryId = localStorage.getItem("OutStorage_categoryId")
    var managerId = app.getManagerId()
    $.ajax({
      url: app.ServerUrl + 'v1/type/getMaterialBrandAndModelPoByTypicalName/' +
        typicalName + "?managerId=" + managerId + "&categoryId=" + categoryId,
      type: "get",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      async: true,
      headers: {
        "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
      },
      data: {},
      success: function (data) {
        // console.log(data.objs[0])
        var typeData = data.objs[0];
        var typeHtml = "<option>请选择型号</option>";
        for (let i = 0; i < typeData.length; i++) {
          var Arry = typeData[i];
          for (let j = 0; j < Arry.modelPo.length; j++) {
            typeHtml += '<option  value="' + Arry.modelPo[j].typicalId + '">' +
              Arry.modelPo[j].typicalModel +
              '</option>'
          }
        }
        model.innerHTML = typeHtml;
        form.render("select")
      },
      error: function (e) {
        console.log(e.statusText)
      }

    })
  }

  form.on("submit(find_people)", function (data) {
    var Info = app.getUserGlobalInfo();
    var workId = data.field.workId;
    $.ajax({
      url: app.ServerUrl + '/v1/repository/getRepositoryInfoByWorkId',
      type: "get",
      contentType: "application/json;charset=UTF-8",
      dataType: "json",
      async: true,
      headers: {
        "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
      },
      data: {
        tempUserId: Info.userId,
        workId: workId
      },
      success: function (data) {
        // console.log(data.objs[0])
        if (data.resultStatus == 1) {
          var typeData = data.objs[0];
          var typeHtml = "<option>请选择此人的仓库</option>";
          for (let i = 0; i < typeData.length; i++) {
            var Arry = typeData[i];
            typeHtml += '<option x-test= "123" value="' + Arry.repositoryId + '">' +
              Arry.repositoryName +
              '</option>'

          }
          repository_opposite.innerHTML = typeHtml;
          form.render("select")
          // find_people.classList.add("layui-hide");
          repository_opposite_div.classList.remove("layui-hide");
        } else {
          layer.open({
            content: data.resultIns,
            btnAlign: 'c',
            anim: 5,
            icon: 5,
            cancel: function () {}
          });
        }

      },
      error: function (e) {
        layer.open({
          content: data.resultIns,
          btnAlign: 'c',
          anim: 5,
          icon: 5,
          cancel: function () {}
        });
      }
    })
  })

  // repository的select
  form.on('select(repository_opposite)', function (data) {
    OutStorage_num.classList.remove("layui-hide");
    OutStorage_button.classList.remove("layui-hide");
    var OutStorage_Info = data.value;
  });

  form.on('submit(search)', function (data) {
    // console.log(data.field);
    var result = data.field;
    var Info = app.getUserGlobalInfo();
    // console.log(Info)
    // console.log(Info.userId)
    layer.confirm('确认要执行出库操作吗？', {
      title: '提示信息',
      icon: 3,
      btn: ['确认', '取消'],
      yes: function (index) {
        var aimWorkId = document.getElementById("workId").value;
        // console.log(aimWorkId)
        $.ajax({
          url: app.ServerUrl + 'v1/material/outStorageMaterial/' + result.category,
          type: "post",
          contentType: "application/json;charset=UTF-8",
          dataType: "json",
          async: true,
          headers: {
            "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
          },
          data: JSON.stringify({
            count: result.outstorage_num,
            materialTypicalId: result.typicalId,
            operator: Info.userId,
            sourceRepositoryId: result.repository_mine,
            targetRepositoryId: result.repository_opposite,
            aimWorkId: aimWorkId
          }),
          success: function (data) {
            // console.log(data)
            $.ajax({
              url: app.ServerUrl + 'v1/repository/getThingsInRepositoryByCondition',
              type: "get",
              contentType: "application/json;charset=UTF-8",
              dataType: "json",
              async: true,
              headers: {
                "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
              },
              data: {
                categoryId: result.category,
                repositoryId: result.repository_mine,
                typicalId: result.typicalId,
                userId: Info.userId
              },
              success: function (data) {
                // console.log(data.objs[0])
                var typeData = data.objs[0];
                var typeHtml = "";
                for (let i = 0; i < typeData.length; i++) {
                  typeHtml +=
                    '<tr>' +
                    '<td> ' + typeData[i].imei + ' </td>  <' +
                    'td > ' + typeData[i].categoryName + ' </td>  <' +
                    'td > ' + typeData[i].typicalName + ' </td> <' +
                    'td > ' + typeData[i].brand + ' </td> <' +
                    'td > ' + typeData[i].typicalModel + ' </td>' +
                    '</tr>'
                }
                $('#tabale-thd').removeClass('layui-hide');
                table_tby.innerHTML = typeHtml;
              },
              error: function (e) {
                console.log(e.statusText)
              }
            });
            // 出库成功提示框
            layer.open({
              content: '出库成功！',
              btnAlign: 'c',
              anim: 5,
              icon: 6,
              cancel: function () {},
            });

          },
          error: function (e) {
            layer.open({
              content: '出库失败！',
              btnAlign: 'c',
              anim: 5,
              icon: 5,
              cancel: function () {}
            });
          }
        })
        layer.close(index);
      },
      cancel: function (index) {
        layer.close(index);
      }
    })
  })

});

var managerId = app.getManagerId();

// 根据条件查询用户相应信息
$('#search').click(function () {
  // var workId = $('#workId').val().trim();
  var username = $('#username').val().trim();
  if (username === '') {
    layer.msg('查询内容不能为空！', {
      icon: 5,
      time: 1000
    });
  } else {
    var url = '';

    url = app.ServerUrl + "v1/user/queryUser?username=" + username + "&managerId=" + managerId;

    check(url);
  }
  return false;
})

// 根据条件查询用户相应信息的数据请求
function check(url) {
  $.ajax({
    url: url,
    dataType: "json",
    type: "POST",
    async: false,
    data: {},
    headers: {
      "Authorization": "460bcdb0-b326-4d6d-ac99-232c83ba6d80"
    },
    success: function (responseData) {
      if (responseData.resultStatus == 1) {
        var result = responseData.objs[0];
        if (result == '' || result == null) {
          layer.msg('查无此人', {
            icon: 5,
            time: 1000
          })
        }
        dataRender(result);
      } else {
        layer.msg(responseData.resultIns, {
          icon: 5,
          time: 1000
        })
      }
    },
    error: function () {
      layer.msg('数据请求失败', {
        icon: 5,
        time: 1000
      })
    }
  })
}

// 渲染用户信息表格函数
function dataRender(result) {
  $('#findResults').empty();
  var str =
    '<thead>' +
    '<tr>' +
    '<th>工号</th>' +
    '<th>用户名</th>' +
    '<th>性别</th>' +
    '<th>年龄</th>' +
    '<th>用户归属</th>' +
    '</tr>' +
    '</thead>' +
    '<tbody id="tbody">';

  for (i = 0; i < result.length; i++) {

    var sex = '';
    if (result[i].sex === "1") {
      sex = '男';
    } else {
      sex = '女';
    }
    if (result[i].status == 1) {

      str += '<tr>' +
        '<td>' + result[i].workId + '</td>' +
        '<td>' + result[i].username + '</td>' +
        '<td>' + sex + '</td>' +
        '<td>' + result[i].age + '</td>' +
        '<td>' + result[i].role + '</td>' +
        '</tr>'
    } else {
      str += '<tr>' +
        '<td>' + result[i].workId + '</td>' +
        '<td>' + result[i].username + '</td>' +
        '<td>' + sex + '</td>' +
        '<td>' + result[i].age + '</td>' +
        '<td>' + result[i].role + '</td>' +
        '</tr>'
    }

  }
  str += '</tbody>'
  $('#findResults').append(str);
}